<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '注册商家',
  },
}
</route>

<template>
  <view class="min-h-screen bg-gray-100 px-4 py-12">
    <view class="bg-white rounded-2xl p-6 shadow space-y-5">
      <!-- 头像 -->
      <view @click="chooseImage" class="flex justify-center mb-2">
        <view class="relative w-20 h-20">
          <image
            class="w-full h-full rounded-full object-cover border border-gray-200"
            :src="uploadedImage || avatarUrl"
            mode="aspectFill"
          />
        </view>
      </view>

      <!-- 姓名 -->
      <view>
        <view class="text-gray-400 text-sm mb-1">姓名</view>
        <input
          class="h-12 bg-gray-100 rounded-full px-4 mx-2 w-auto"
          v-model="name"
          placeholder="请输入姓名"
        />
      </view>

      <!-- 商家类型 -->
      <view>
        <view class="text-gray-400 text-sm mb-1">商家类型</view>
        <view class="flex flex-wrap gap-3 mx-2 mt-2">
          <view
            v-for="item in merchantTypes"
            :key="item"
            @click="type = item"
            :class="[
              'px-4 py-2 rounded-full text-sm border',
              type === item
                ? 'bg-[#6C4CFF] text-white border-[#6C4CFF]'
                : 'bg-gray-100 text-gray-700 border-gray-200',
            ]"
          >
            {{ item }}
          </view>
        </view>
      </view>

      <!-- 商家名称 -->
      <view>
        <view class="text-gray-400 text-sm mb-1">商家小区名称</view>
        <input
          class="h-12 bg-gray-100 rounded-full px-4 mx-2 w-auto"
          v-model="merchantName"
          placeholder="请输入小区名称"
        />
      </view>

      <!-- 手机号 -->
      <view>
        <view class="text-gray-400 text-sm mb-1">手机号</view>
        <input
          class="h-12 bg-gray-100 rounded-full px-4 mx-2 w-auto"
          v-model="phone"
          placeholder="请输入手机号"
        />
      </view>
      <!-- 密码 -->
      <view>
        <view class="text-gray-400 text-sm mb-1">密码</view>
        <input
          class="h-12 bg-gray-100 rounded-full px-4 mx-2 w-auto"
          v-model="password"
          placeholder="请输入密码"
        />
      </view>

      <!-- 地址 -->
      <view>
        <view class="text-gray-400 text-sm mb-1">地区</view>
        <view class="flex flex-col space-y-2">
          <!-- 省市区选择器 -->
          <view class="h-12 bg-gray-100 rounded-full px-4 mx-3 w-auto">
            <picker
              mode="region"
              @change="bindRegionChange"
              :value="region"
              class="h-full w-full flex items-center justify-between"
            >
              <view class="flex items-center justify-between w-full">
                <text v-if="region.length > 0" class="text-black">{{ region.join(' ') }}</text>
                <text v-else class="text-gray-400">请选择省市区</text>
                <uni-icons type="right" size="14" color="#999"></uni-icons>
              </view>
            </picker>
          </view>
        </view>
      </view>

      <view>
        <!-- 详细地址输入框 -->
        <view class="text-gray-400 text-sm mb-1">详细地址</view>
        <input
          class="h-12 bg-gray-100 rounded-full px-4 mx-2 w-auto"
          v-model="addressDetail"
          placeholder="请输入详细地址"
        />
      </view>

      <!-- 商家图片 -->
      <!-- <view>
        <image class="w-full h-36 rounded-xl object-cover" :src="merchantImg" mode="aspectFill" />
      </view> -->

      <!-- 保存按钮 -->
      <button
        class="w-full h-12 bg-[#6C4CFF] text-white rounded-xl text-lg font-medium mt-2 flex items-center justify-center"
        @click="onSave"
      >
        保存
      </button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, watch, computed } from 'vue'
import { getRegister } from '@/service/index/foo'

const avatarUrl = ref('https://kuaidi.trio.pub/upload/uniapp/delivery/sctp.png') // 默认头像图标
const uploadedImage = ref('') // 存储上传后的图片URL显示用
const picPath = ref('') // 存储上传后服务器返回的pic_path值
const merchantTypes = ['服务中心', '快递公司', '同城商家']

const name = ref('')
const type = ref('')
const merchantName = ref('')
const phone = ref('')
const password = ref('')
const address = ref('') // 完整地址，由region和addressDetail组合
const region = ref<string[]>([]) // 省市区
const addressDetail = ref('') // 详细地址

// 提取省市区到独立变量，方便发送给后端
const province = computed(() => region.value[0] || '')
const city = computed(() => region.value[1] || '')
const district = computed(() => region.value[2] || '')

// 监听地址变化，组合成完整地址（保留以保持向后兼容性）
watch([region, addressDetail], () => {
  if (region.value.length > 0 && addressDetail.value) {
    address.value = region.value.join(' ') + ' ' + addressDetail.value
  } else {
    address.value = ''
  }
})

const onBack = () => {
  uni.navigateBack()
}

// 地区选择事件
const bindRegionChange = (e) => {
  console.log('Region changed:', e.detail.value)
  region.value = e.detail.value
}

const onSave = async () => {
  try {
    if (
      !name.value ||
      !type.value ||
      !merchantName.value ||
      !phone.value ||
      !region.value.length ||
      !addressDetail.value ||
      !password.value
    ) {
      uni.showToast({
        title: '请填写完整信息',
        icon: 'none',
      })
      return
    }

    uni.showLoading({ title: '提交中...' })

    const res = await getRegister({
      username: name.value, // 用户名
      shop_type: type.value, // 商家类型
      shop_name: merchantName.value, // 商家名称
      mobile: phone.value, // 手机号
      password: password.value, // 密码
      province: province.value, // 省份
      city: city.value, // 城市
      district: district.value, // 区/县
      address: addressDetail.value, // 详细地址
      avatar: 'https://kuaidi.trio.pub' + uploadedImage.value, // 优先使用pic_path值
    })

    uni.hideLoading()
    console.log(res)

    if (res.code === 0) {
      // 成功情况
      const successMessage = typeof res.data === 'string' ? res.data : '注册成功'
      uni.showModal({
        title: '提示',
        content: successMessage,
        showCancel: false,
        success: () => {
          // 注册成功后可以跳转到首页或登录页
          uni.reLaunch({ url: '/pages/login/index' })
        },
      })
    } else if (res.code === -1) {
      // 错误情况，如手机号已注册
      const errorMessage = typeof res.data === 'string' ? res.data : '注册失败'
      uni.showModal({
        title: '提示',
        content: errorMessage,
        showCancel: false,
      })
    } else {
      // 其他错误情况
      uni.showModal({
        title: '提示',
        content: typeof res.data === 'string' ? res.data : '操作失败',
        showCancel: false,
      })
    }
  } catch (error) {
    uni.hideLoading()
    console.error('注册失败:', error)
    uni.showModal({
      title: '提示',
      content: error.data.data || '操作失败',
      showCancel: false,
    })
  }
}

// 添加头像选择和上传功能
const chooseImage = () => {
  uni.chooseImage({
    count: 1, // 默认9
    sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'], // 从相册选择或拍照
    success: function (res) {
      // 返回选定照片的本地文件路径列表
      const tempFilePath = res.tempFilePaths[0]

      // 先将选择的图片显示出来，提升用户体验
      // uploadedImage.value = tempFilePath

      // 上传图片到服务器
      uploadImageFile(tempFilePath)
    },
  })
}

// 直接上传图片文件到服务器
const uploadImageFile = (filePath) => {
  uni.showLoading({
    title: '上传中...',
    mask: true,
  })

  console.log('准备上传图片:', filePath)

  // 使用uploadFile方法直接上传文件
  uni.uploadFile({
    url: 'https://kuaidi.trio.pub/api/upload/uploadimg',
    filePath,
    name: 'file', // 文件对应的 key
    formData: {},
    success: (uploadRes) => {
      uni.hideLoading()
      console.log(uploadRes)
      uploadedImage.value = 'https://kuaidi.trio.pub/' + JSON.parse(uploadRes.data).data.pic_path
    },
    fail: (error) => {
      console.error('上传请求失败:', error)
      uni.hideLoading()
      // 不清空uploadedImage，保留用户选择的图片
      uni.showToast({
        title: '图片已选择',
        icon: 'success',
        duration: 1500,
      })
    },
  })
}
</script>

<style scoped>
page {
  background-color: #f3f4f6; /* gray-100 in tailwind */
}
</style>
